#include <stdio.h>

#include "thread.h"
#include "ipc.h"

#define USING_STATIC
#define USING_MUTEX

#ifdef USING_MUTEX
#ifdef USING_STATIC
static mt_mutex_t lock;
#endif
static mt_mutex_t *lock_p;
#endif

static char str[] = "1234567890\r\n";

    
static void *thread1_func(void *arg)
{
    char *p = arg;
    int i;
    
    printf("%s\r\n", p);
    while(1)
    {
#ifdef USING_MUTEX
        if(mt_mutex_take(lock_p, MT_WAITING_FOREVER) == MT_EOK)
        {
#endif
            for(i=0; i<sizeof(str); i++)
            {
                printf("%c", str[i]);
                mt_delay(10);
            }
#ifdef USING_MUTEX
            mt_mutex_release(lock_p);
        }
        else
            printf("take lock failed\r\n");
#endif
    }
}

static void *thread2_func(void *arg)
{
    char *p = arg;
    int i;
    
    printf("%s\r\n", p);
    while(1)
    {
#ifdef USING_MUTEX
        if(mt_mutex_take(lock_p, MT_WAITING_FOREVER) == MT_EOK)
        {
#endif
            for(i=0; i<sizeof(str); i++)
            {
                printf("%c", str[i]);
                mt_delay(10);
            }
#ifdef USING_MUTEX
            mt_mutex_release(lock_p);
        }
        else
            printf("take lock failed\r\n");
#endif
    }
}


int mutex_test(void)
{
    mt_thread_t *thread1_handle;
    mt_thread_t *thread2_handle;
    
#ifdef USING_MUTEX
#ifdef USING_STATIC
    mt_mutex_init(&lock, "test_lock", MT_IPC_FLAG_FIFO);
    lock_p = &lock;
#else
    lock_p = mt_mutex_create("test_lock", MT_IPC_FLAG_FIFO);
    if(lock_p == MT_NULL)
    {
        printf("create mutex faied\r\n");
        return -1;
    }
#endif
#endif
    
    thread1_handle = mt_thread_create("thread1", 
                                      thread1_func, 
                                      "thread1", 
                                      2048, 
                                      2, 
                                      5);
    thread2_handle = mt_thread_create("thread2", 
                                      thread2_func, 
                                      "thread2", 
                                      2048, 
                                      1, 
                                      5);
    if((thread1_handle == MT_NULL) || (thread2_handle == MT_NULL))
    {
        printf("create thrtead faied\r\n");
        return -1;
    }
    mt_thread_start(thread1_handle);
    mt_thread_start(thread2_handle);
    
    return 0;
}
